package com.pig4cloud.pig.customer.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.customer.service.CustomerService;
import com.pig4cloud.pig.customer.vo.TrCustomer;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpHeaders;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/customer")
@Tag(description = "customer",name="客户管理")
@RequiredArgsConstructor
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class CustomerController {
	private final CustomerService customerService;
//	客户管理页面分页
	@GetMapping("/page")
	// @ParameterObject注解用于将请求参数自动封装到Page对象和TrCustomer对象中
	public R<Page<TrCustomer>> pageCustomers(@ParameterObject Page page, @ParameterObject TrCustomer trCustomer) {
		Page<TrCustomer> resultPage = customerService.pageCustomers(page, trCustomer);
		return R.ok(resultPage);
	}
	// 根据客户id查询客户信息（带统计）
	@GetMapping("/detail")
	public R<TrCustomer> getDetails(@RequestParam("cusId") Long cusId) {
		if(cusId ==null || cusId<=0){
			return R.failed("无效的客户ID");
		}
		TrCustomer customer = customerService.getByIdWithCount(cusId);
		if(customer ==null){
			return R.failed("未找到客户信息");
		}
		return R.ok(customer);
	}
//	新增客户信息
	@PostMapping("/add")
	public R addCustomer(@RequestBody TrCustomer customer){
		return customerService.addCustomer(customer);
	}
	// 新增：手机号唯一性校验接口（供前端调用）
	@GetMapping("/checkTel")
	public R<Boolean> checkTelExists(
			@RequestParam String cusTel,
			@RequestParam(required = false) Long cusId) {
		return customerService.checkTelExists(cusTel, cusId);
	}

	//	修改客户信息
	@PutMapping("/update")
	public R updateCustpmer(@RequestBody TrCustomer customer) {
		if (customer.getCusId() == null) {
			return R.failed("客户ID不能为空");
		}
		// 调用Service的校验逻辑（复用validateTel）
		R validateResult = customerService.validateTel(customer, false);
		if (!validateResult.isSuccess()) {
			return validateResult;
		}
		boolean success = customerService.updateById(customer);
		return success ? R.ok("修改成功") : R.failed("修改失败");

	}

}
